const Axios = require('axios')
const Cheerio = require('cheerio')
const vm = require('vm')
const process = require('process')
const fs = require('fs-extra')
const schedule = require('node-schedule')
const ejs = require("ejs"); //模板
const moment = require("moment"); //日期
const { mailSend } = require("./mail"); // 发邮件

const url = `https://3g.dxy.cn/newh5/view/pneumonia_peopleapp?from=timeline&isappinstalled=0`
async function getData(){
    let response = await Axios.get(url);
    let html = await response.data;
    let $ = Cheerio.load(html);
    let script = $('body > script');
    console.log(script.length);
    var global = {
        window:{}
    };
    for(let i = 0; i < script.length; i++){
        if(script[i] && script[i].children.length>0){
            let scriptContent = script[i].firstChild.data;
            vm.createContext(global);
            vm.runInContext(scriptContent, global);
        }
    }
    return global.window;
}

async function main(){
    // let data = await getData();
    console.log('开始采集...')
    let data = await getData() || {};
    try {
        let cache = await fs.readJSON('./resource/data.json');
        if(cache){
            let keys = Object.keys(cache);
            for(let i = 0; i < keys.length; i++){
                let key = keys[i];
                // ### 测试中发现数据源可能会产生丢失部分数据的问题，如果缺少某项数据，复用缓存数据
                data[key] = data[key] || cache[key];
            }
        }  
    } catch (error) {
        console.log('数据源错误', error);
    }
    await fs.writeJSON('./resource/data.json', data ) //保存数据
    let testObj = await fs.readJSON('./resource/data.json')
    console.log( '采集到的数据源长度', Object.keys(testObj).length )
}
// 每周1-7的6点和12点,18点执行
let rule = new schedule.RecurrenceRule();
rule.dayOfWeek =[1,2,3,4,5,6,7];
rule.hour =[6,12,18];
rule.minute =0;
rule.second =0;
schedule.scheduleJob( rule, () => {
    readyMail()
  })

// readyMail()

schedule.scheduleJob('*/5 * * * *', () => {
    main().catch((error) => {
        console.log('采集 err',error);
        process.exit();
    })
    // readyMail()
  })
  

let staticData = {} // 整体数据
let proviceData = [] // 省份数据
async function readyMail() {
    let covFileSta = await fs.readJSON('./resource/data.json')   
    let areaStat = covFileSta.getAreaStat; 
    // 填入省份数组     
    for(let i = 0; i < areaStat.length; i++){
        let area = areaStat[i];
        proviceData.push(
            {
                provinceShortName: area.provinceShortName || '未知区域',
                confirmedCount: area.confirmedCount || 0,
                curedCount: area.curedCount || 0 ,
                deadCount: area.deadCount || 0 ,
                cityNumber: area.cities.length || 0
            })
    }
    // 整体数据数组
    staticData = {
        confirmedCount: covFileSta.getStatisticsService.confirmedCount,
        suspectedCount: covFileSta.getStatisticsService.suspectedCount,
        curedCount: covFileSta.getStatisticsService.curedCount,
        deadCount: covFileSta.getStatisticsService.deadCount,
        // seriousCount: covFileSta.getStatisticsService.seriousCount
    }
    // console.log('测试daaa\n', staticData )
    try {		
		// 邮件模板发送html
		let data = {staticData, proviceData}
		ejs.renderFile('./resource/mail_tmp.ejs', data, {}, function(err, str){
            // console.log( '渲染', str, err )   
		    mailSend( 'nCov今日疫情数据 ', str)
		});

	} catch(error) {
		console.log('EAMIL SEND', error);
	} finally {
		//清空
		staticData = {};
		proviceData = [];
	}
}

// readyMail()


// 邮件发送部分--每天17点30 发邮件
// schedule.scheduleJob('30 30 17 * * *', () => {
	// try {		
	// 	//使用ejs 模板引擎发送html 内容 2018-05-13 
	// 	let data = {staticData, proviceData}
	// 	ejs.renderFile('./mail_tmp.ejs', data, {}, function(err, str){
	// 	    mailSend(new Date().Format("yyyy-MM-dd") + 'nCov今日疫情数据', str)
	// 	});

	// } catch(error) {
	// 	console.log('EAMIL SEND', error);
	// } finally {
	// 	//清空
	// 	staticData = {};
	// 	proviceData = [];
	// }
// });

